package mygang.service.manager;

import mygang.dao.manager.RoleDAO;
import mygang.model.Role;
import org.springframework.stereotype.Service;

/**
 *
 * @author Volodymyr Lavrynovych <volodya.lavrynovych@gmail.com>
 */
@Service("roleService")
public class RoleServiceImpl<D extends RoleDAO> extends AbstractManageService<D, Role> implements RoleService {

    public void add(Role role) throws Exception {
        role.setName(checkRoleName(role.getName()));
        
        try {
            getDao().save(role);
        } catch (Exception ex) {
            String message = "";
            Throwable throwable = ex;
            do {
                if (throwable.getMessage().indexOf("UK_ROLE_NAME") != -1) {
                    message = "Role with the same name already exists";
                    log.error(message + "\n" + ex);
                }
            } while ((throwable = throwable.getCause()) != null);
            throw new Exception(message, ex);
        }
    }
    
    public void update(Role role) throws Exception {
        role.setName(checkRoleName(role.getName()));
        getDao().save(role);
    }
    
    @Override
    public Role findByName(String roleName) {
        return getDao().findByName(checkRoleName(roleName));
    }
    
    private String checkRoleName(String roleName){
        if(roleName.length() > 5 && roleName.substring(0, 5).toUpperCase().equals("ROLE_")) {
            return roleName.toUpperCase();
        } else {
            return "ROLE_" + roleName.toUpperCase();
        }
    }
}